/**
 * 构建TCP客户端
 */

/* 引入net模块 */
var net = require("net");

/* 创建TCP客户端 */
var client = net.Socket();

/* 设置连接的服务器 */


var curSocket = null;
var state = "default";
var jsonData = "";
/* 监听服务器传来的data数据 */
client.on("data", function (data) {
 
    if (state == "proxy")
    {
        curSocket.write(data);
        return;
    }
})

/* 监听end事件 */
client.on("end", function () {
    console.log("data end");
    curSocket.end();
})

client.on('error',(err)=>{
});
client.connect(4001, '127.0.0.1', function () {
    console.log("connect the server");
    console.log('got a new connection ',client.localAddress,client.localPort,"remote",client.remoteAddress,client.remotePort);
    /* 向服务器发送数据 */
    var data = {
        msgtype:"request",
        type:"SSH",
        ip:"sghz001032006",
        port:22,
        timeout:5000
    };
    client.write(JSON.stringify(data));
    // 这里打开外部工具
})
 var server = net.createServer();
 server.on('connection', function(socket) {
     console.log("got connection");
    curSocket = socket;
    state = "proxy";
    var data = {
        msgtype:"start",
    };

    client.write(JSON.stringify(data));
    socket.on('data', function(data) {
        client.write(data);
     });

     socket.on('close', function() {
         // 同步列表信息
        client.end();
     });
     socket.on('error',(err)=>{
          client.end();
          // 同步列表信息
     });
 });
 
  server.on('error', function(err) {
    client.end();
     console.log('Server error:', err.message);

 });

 server.on('close', function() {
    client.end();
     console.log('Server closed');

 });

 server.listen(4003);